<?php

use Phphub\Core\CreatorListener;

class SectionsController extends \BaseController implements CreatorListener
{
    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('auth', ['only' => ['edit', 'store', 'update', 'destroy']]);
    }

    public function authorOrAdminPermissioinRequire($author_id)
    {
        if (! Entrust::can('manage_sections') && $author_id != Auth::id()) {
            throw new ManageSectionsException("permission-required");
        }
    }

    public function store()
    {
        return App::make('Phphub\Creators\SectionCreator')->create($this, Input::except('_token'));
    }

    public function edit($id)
    {
        $section = Section::findOrFail($id);
        $this->authorOrAdminPermissioinRequire($section->user_id);
        $lab = $section->lab;
        $node = $lab->node;

        $section->body = $section->body_original;

        return View::make('sections.create_edit', compact('section', 'lab', 'node'));
    }

    public function show($id)
    {
        $section = Section::findOrFail($id);

        $lab = $section->lab;
        $node = $lab->node;

        return View::make('sections.show', compact('section', 'lab', 'node'));
    }

    public function update($id)
    {
        $section = Section::findOrFail($id);
        $data = Input::only('title', 'body', 'experiment_url', 'lab_id');

        $this->authorOrAdminPermissioinRequire($section->user_id);

        $markdown = new Markdown;
        $data['body_original'] = $data['body'];
        $data['body'] = $markdown->convertMarkdownToHtml($data['body']);

        // Validation
        App::make('Phphub\Forms\SectionCreationForm')->validate($data);

        $section->update($data);

        Flash::success(lang('Operation succeeded.'));
        return Redirect::route('labs.show', $section->lab_id);
    }

    public function vote($id)
    {
        $section = Section::find($id);
        App::make('Phphub\Vote\Voter')->sectionUpVote($section);
        return Redirect::route('labs.show', [$section->lab_id, '#section'.$section->id]);
    }

    public function destroy($id)
    {
        $section = Section::findOrFail($id);
        $this->authorOrAdminPermissioinRequire($section->user_id);
        $section->delete();

        Flash::success(lang('Operation succeeded.'));

        return Redirect::route('labs.show', $section->lab_id);
    }

    /**
     * ----------------------------------------
     * CreatorListener Delegate
     * ----------------------------------------
     */

    public function creatorFailed($errors)
    {
        Flash::error(lang('Operation failed.'));
        return Redirect::back();
    }

    public function creatorSucceed($section)
    {
        Flash::success(lang('Operation succeeded.'));
        return Redirect::route('labs.show', ['lab_id' => $section->lab_id]);
    }
}
